package com.hsnn.medstgmini.pro.project.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.std.model.StdCompinfo;
import com.hsnn.medstgmini.base.std.model.StdCompprofile;
import com.hsnn.medstgmini.base.std.model.StdCompprofileLog;
import com.hsnn.medstgmini.pro.project.model.BidProjcompprofile;
import com.hsnn.medstgmini.pro.project.model.BidProjcompprofileLog;
import com.hsnn.medstgmini.pro.project.model.BidProjectDetails;
import com.hsnn.medstgmini.pro.project.model.form.ProdProfileForm;
import com.hsnn.medstgmini.pro.project.service.BidProjcompprofileManager;
import com.hsnn.medstgmini.pro.project.service.ProdProfileManager;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.DateUtil;
import com.hsnn.medstgmini.util.DbUtil;
import com.hsnn.medstgmini.util.ImgUtil;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.ParseDate;

@Controller
@RequestMapping("/bidProjcompprofile")
public class BidProjcompprofileController {
    private static final Logger log = Logger.getLogger(BidProjcompprofileController.class);

	@Autowired
	private BidProjcompprofileManager bidProjcompprofileManager;
	
	@Autowired
	private ProdProfileManager prodProfileManager;
	
	@Autowired
	private HttpServletRequest request;
	
	@Autowired
	private HttpSession session;
	
	/**
	 *@category 企业资质申报页面【项目】
	 *@author 应晓川
	 *@date 2015年8月27日09:58:56
	 *@return
	 */
	@RequestMapping("/toCompprofileProj")
	public String toCompprofileProj(Model model,RedirectAttributes attr){
		SysUser user = (SysUser)request.getSession().getAttribute(Constants.USERINFO);
		String defalutProjId=  user.getDefaultProjId();
		if ( StringUtils.isNotBlank(defalutProjId) ) {
			 attr.addAttribute("projId",defalutProjId);  
		     return "redirect:/bidProjcompprofile/toCompprofileList.html";
		}
		model.addAttribute("date", ParseDate.parseShortFormat(new Date()));
		return "/pro/project/bidProjcompprofile/projCompprofile";
	}
	
	/**
	 *@category 企业资质申报结果页面【项目】
	 *@author 应晓川
	 *@date 2015年8月27日09:58:56
	 *@return
	 */
	@RequestMapping("/toAuditResultProj")
	public String toAuditResultProj(){
		request.setAttribute("date", ParseDate.parseShortFormat(new Date()));
		return "/pro/project/bidProjcompprofile/projAuditResult";
	}
	
	/**
	 *@category 企业资澄清页面【项目】
	 *@author 应晓川
	 *@date 2015年8月27日09:58:56
	 *@return
	 */
	@RequestMapping("/toComplainProj")
	public String toComplainProj(){
		request.setAttribute("date", ParseDate.parseShortFormat(new Date()));
		return "/pro/project/bidProjcompprofile/projComplain";
	}
	
	/**
	 *@category 企业资澄清结果页面【项目】
	 *@author 应晓川
	 *@date 2015年8月27日09:58:56
	 *@return
	 */
	@RequestMapping("/toComplainResultProj")
	public String toComplainResultProj(){
		request.setAttribute("date", ParseDate.parseShortFormat(new Date()));
		return "/pro/project/bidProjcompprofile/projComplainResult";
	}
	
	/**
	 * @category 获取项目列表数据
	 * @author 应晓川
	 * @date 2015年8月27日09:59:53
	 * @return
	 */
	@RequestMapping("/getDataList")
	@ResponseBody
	public Pagination getDataList() {
		Pagination page = new Pagination(request);
		try {
			DbUtil.jsonToMap(request, page);
			bidProjcompprofileManager.getBidProjectList(page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	/**
	 * @category 获取项目列表数据
	 * @author 应晓川
	 * @date 2015年8月27日09:59:53
	 * @return
	 */
	@RequestMapping("/getBidProjCompanyList")
	@ResponseBody
	public Pagination getBidProjCompanyList() {
		Pagination page = new Pagination(request);
		try {
			DbUtil.jsonToMap(request, page);
			bidProjcompprofileManager.getBidProjectList(page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	/**
	 *@category 去资质管理
	 *@author 应晓川
	 *@date 2015年8月27日16:45:53
	 *@return
	 */
	@RequestMapping("/toCompprofileList")
	public String toCompprofileList(Model model,String projId){
		log.info("enter toCompprofileList method!");
		model.addAttribute("projId", projId);
		return "/pro/project/bidProjcompprofile/compprofileList";
	}
	
	/**
	 *@category 获取企业资质列表数据
	 *@author 应晓川   修改人：韩守松
	 *@date 2015年8月27日16:45:53 修改日期 2015-09-23
	 *@return
	 */
	@RequestMapping("/getCompprofileList")
	@ResponseBody
	public Pagination getCompprofileList(ProdProfileForm form){
		Pagination page = new Pagination(request);
		try {
		SysUser user=(SysUser) request.getSession().getAttribute(Constants.USERINFO);
		StdCompinfo compInfo = user.getInfo();
			if (compInfo != null) {
				String compId = compInfo.getCompId();
				String projId = user.getDefaultProjId();
				if(StringUtils.isNotBlank(projId)){
					form.setProjId(projId);
				}
				page.setForm(form);
				page.getConditions().put("projId", form.getProjId());
				if (StringUtils.isNotBlank(compId)) {
					form.setCompId(compId);
					page.setForm(form);
					page.getConditions().put("compId", form.getCompId());
					page = bidProjcompprofileManager.getBidProjcompprofileList(page);
					if(StringUtils.isNotBlank(user.getDefaultProjId())){
						BidProjectDetails bidProjectDetails =prodProfileManager.getBidProjectDetailsById(user.getDefaultProjId());
						if(bidProjectDetails.getProSubmitEndtime()!=null && bidProjectDetails.getProjStarttime()!=null && bidProjectDetails.getProSubmitEndtime().getTime()>=new Date().getTime() ){
							page.setForm(Constants.DEFAULT_PROJ_1);//默认项目并且该项目在申报时间段内
						}else{
							page.setForm(Constants.DEFAULT_PROJ_2);//默认项目并且该项目不在申报时间段内
						}
					}else{
						page.setForm(Constants.DEFAULT_PROJ_3);//全部项目，为分离项目
					}
					page.setSuccess(true);
				}
			}
		
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	
	/**
	 *@category 新增企业资质
	 *@author 应晓川
	 *@date 2015年8月27日19:26:16
	 *@return
	 */
	@RequestMapping("/addCompprofile")
	@ResponseBody
	public Pagination addCompprofile(StdCompprofile stdCompprofile ,MultipartFile licence){
		Pagination page = new Pagination(request);
		SysUser user=(SysUser) request.getSession().getAttribute(Constants.USERINFO);
		String compId = ((StdCompinfo )user.getInfo()).getCompId();
		FileOutputStream fos = null;
		try {
//			List<StdCompprofile> list = bidProjcompprofileManager.getBidProjcompprofileListByName(stdCompprofile.getProfileName());
//			if (!(list.size()>0)) {
//				//TODO 名称判断重复
//			}else{
//				page.setSuccess(false);
//				page.setMsg("企业资质名称已被使用！");
//			}
			if (licence != null) {
				if (licence.getSize() > 3 * 1024 * 1024) {
					page.setSuccess(false);
					page.setMsg("资质图片不能大于3M！");
					return page;
				}
				String name = licence.getOriginalFilename();
				if (!ImgUtil.isImg(name)) {
					page.setSuccess(false);
					page.setMsg("请选择格式正确的资质图片，图片支持格式：gif, jpg, jpeg, png, bmp！");
					return page;
				}
				
				int index = name.lastIndexOf(".");
				String suffix = name.substring(index);
				name = ParseDate.parseWithNum(new Date()).toString()+suffix;
				String path = session.getServletContext().getRealPath("/");
				path = path.replaceAll("\\\\", "/") + "upload/licence/";
				
				String filename = path + name;
				File file = new File(filename);
				fos = new FileOutputStream(file);
				InputStream stream = licence.getInputStream();
			    byte[] bytes = new byte[1024];
			    int length = 0;
			    while((length = stream.read(bytes)) !=-1){
			    	fos.write(bytes, 0, length);
			    }
			    fos.flush();
			    stream.close();
			    stdCompprofile.setProfilePicAddr("upload/licence/" + name);
			    stdCompprofile.setProfilePicShortcutAddr("upload/licence/" + name);
			}else{
				page.setSuccess( false );
				page.setMsg("请上传资质图片！");;
				return page;
			}
			stdCompprofile.setCompprofileId(UUID.randomUUID().toString());
			stdCompprofile.setCompId(compId);
			stdCompprofile.setProfileCode("ZZ"+System.currentTimeMillis());//资质编码
			stdCompprofile.setStatus(Constants.OP_TYPE_EDIT);//新增状态0.停用  1.启用
			stdCompprofile.setUpdDatetime(new Date());
			stdCompprofile.setUpdUser(user.getId());
			if(bidProjcompprofileManager.save(stdCompprofile)){
				StdCompprofileLog stdCompprofileLog = new StdCompprofileLog();
				BeanUtils.copyProperties(stdCompprofileLog, stdCompprofile);
				stdCompprofileLog.setLogId(UUID.randomUUID().toString());
				bidProjcompprofileManager.save(stdCompprofileLog);
				page.setMsg("操作成功");;
				page.setSuccess( true );
			}
		
			
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return page;
	}
	/**
	 *@category 提交企业资质
	 *@author 应晓川
	 *@date 2015年8月28日10:59:35
	 *@return
	 */
	@RequestMapping("/commitCompprofile")
	@ResponseBody
	public Pagination commitCompprofile(String array,String projId){
		Pagination page = new Pagination(request);
		SysUser user=(SysUser) request.getSession().getAttribute(Constants.USERINFO);
		//String compId = ((StdCompinfo )user.getInfo()).getCompId();
		try {
			 String[] compprofileIds = array.split(",");
			for(String compprofileId : compprofileIds){
				BidProjcompprofile bidProjcompprofile = new BidProjcompprofile();
				bidProjcompprofile.setProjCompprofileId(UUID.randomUUID().toString());
				bidProjcompprofile.setCompprofileId(compprofileId);
				bidProjcompprofile.setProjId(projId);
				bidProjcompprofile.setApplyType(Constants.APPLYTYPE_1); //申请类型0修改申报1新增申报
				bidProjcompprofile.setStatus(Constants.BIDPROJCOMPROFILE_SATTUS_1);//采购项目企业资质状态0禁用1启用
				Timestamp now =  new Timestamp(new Date().getTime());
				bidProjcompprofile.setUpdDatetime(now);
				bidProjcompprofile.setUpdUser(user.getId());
				if (bidProjcompprofileManager.save(bidProjcompprofile)) {
					BidProjcompprofileLog bidProjcompprofileLog = new BidProjcompprofileLog();
					BeanUtils.copyProperties(bidProjcompprofileLog, bidProjcompprofile);
					bidProjcompprofileLog.setUpdDatetime(now);
					bidProjcompprofileLog.setLogId(UUID.randomUUID().toString());
					bidProjcompprofileManager.save(bidProjcompprofileLog);
					page.setMsg("操作成功");;
					page.setSuccess( true );
				}
			}
			
			
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	/**
	 *@category 去查看审核结果
	 *@author 应晓川
	 *@date 2015年8月27日16:45:53
	 *@return
	 */
	@RequestMapping("/toAuditResult")
	public String toAuditResult(String projId){
		request.setAttribute("projId", projId);
		return "/pro/project/bidProjcompprofile/auditResult";
	}
	
	/**
	 *@category 去查看申报结果
	 *@author 应晓川
	 *@date 2015年8月27日16:45:53
	 *@return
	 */
	@RequestMapping("/toApplyResult")
	public String toApplyResult(String projId){
		request.setAttribute("projId", projId);
		return "/pro/project/bidProjcompprofile/applyResult";
	}
	
	/**
	 *@category 获取企业资质审核结果列表数据
	 *@author 应晓川
	 *@date 2015年8月27日16:45:53
	 *@return
	 */
	@RequestMapping("/getAuditResultList")
	@ResponseBody
	public Pagination getAuditResultList(String projId){
		Pagination page = new Pagination(request);
		SysUser user=(SysUser) request.getSession().getAttribute(Constants.USERINFO);
		String compId = ((StdCompinfo )user.getInfo()).getCompId();
		try {
			page.getConditions().put("projId", projId);
			page.getConditions().put("compId", compId);
			//page.getConditions().put("auditStatus",Constants.SETTLE_STATUS_NEW);//查已提交的资质
			page = bidProjcompprofileManager.getBidProjcompprofileResultList(page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	/**
	 *@category 获取企业资质申报结果列表数据
	 *@author 应晓川
	 *@date 2015年8月27日16:45:53
	 *@return
	 */
	@RequestMapping("/getApplyResultList")
	@ResponseBody
	public Pagination getApplyResultList(String projId){
		Pagination page = new Pagination(request);
		SysUser user=(SysUser) request.getSession().getAttribute(Constants.USERINFO);
		String compId = ((StdCompinfo )user.getInfo()).getCompId();
		try {
			page.getConditions().put("projId", projId);
			page.getConditions().put("compId", compId);
			page = bidProjcompprofileManager.getBidProjcompprofileApplyResultList(page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	/**
	 *@category 去资审澄清
	 *@author 应晓川
	 *@date 2015年8月31日11:10:59
	 *@return
	 */
	@RequestMapping("/toComplain")
	public String toComplain(String projId){
		request.setAttribute("projId", projId);
		return "/pro/project/bidProjcompprofile/noPassResult";
	}
	
	/**
	 *@category 获取企业资质审核未通过的列表数据
	 *@author 应晓川
	 *@date 2015年8月31日11:12:16
	 *@return
	 */
	@RequestMapping("/getNotPassResultList")
	@ResponseBody
	public Pagination getNotPassResultList(String projId){
		Pagination page = new Pagination(request);
		SysUser user=(SysUser) request.getSession().getAttribute(Constants.USERINFO);
		String compId = ((StdCompinfo )user.getInfo()).getCompId();
		try {
			page.getConditions().put("projId", projId);
			page.getConditions().put("compId", compId);
			page.getConditions().put("auditStatus",Constants.SETTLE_STATUS_AUDIT_SUCCESS);//审核未通过
			page = bidProjcompprofileManager.getBidProjcompprofileResultList(page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	/**
	 *@category 澄清未通过审核的企业资质数据
	 *@author 应晓川
	 *@date 2015年8月31日11:12:16
	 *@return
	 */
	@RequestMapping("/complainResult")
	@ResponseBody
	public Pagination complainResult(StdCompprofile stdCompprofile ,MultipartFile licence){
		Pagination page = new Pagination(request);
		SysUser user=(SysUser) request.getSession().getAttribute(Constants.USERINFO);
		FileOutputStream fos = null;
		try {
			BidProjcompprofile bidProjcompprofile = (BidProjcompprofile) bidProjcompprofileManager.getObjectById(BidProjcompprofile.class,stdCompprofile.getProjCompprofileId());
			StdCompprofile stdCompprofileFromDb = (StdCompprofile) bidProjcompprofileManager.getObjectById(StdCompprofile.class, stdCompprofile.getCompprofileId()); 
			if (licence != null) {
				if (licence.getSize() > 3 * 1024 * 1024) {
					page.setSuccess(false);
					page.setMsg("资质图片不能大于3M！");
					return page;
				}
				String name = licence.getOriginalFilename();
				if (!ImgUtil.isImg(name)) {
					page.setSuccess(false);
					page.setMsg("资质请选择图片，图片支持格式：gif, jpg, jpeg, png, bmp！");
					return page;
				}
				
				int index = name.lastIndexOf(".");
				String suffix = name.substring(index);
				name = ParseDate.parseWithNum(new Date()).toString()+suffix;
				String path = session.getServletContext().getRealPath("/");
				path = path.replaceAll("\\\\", "/") + "upload/licence/";
				
				String filename = path + name;
				File file = new File(filename);
				fos = new FileOutputStream(file);
				InputStream stream = licence.getInputStream();
			    byte[] bytes = new byte[1024];
			    int length = 0;
			    while((length = stream.read(bytes)) !=-1){
			    	fos.write(bytes, 0, length);
			    }
			    fos.flush();
			    stream.close();
			    stdCompprofileFromDb.setProfilePicAddr("upload/licence/" + name);
			    stdCompprofileFromDb.setProfilePicShortcutAddr("upload/licence/" + name);
			}
			if (StringUtils.isBlank(stdCompprofileFromDb.getProfilePicAddr())){
				page.setSuccess(false);
				page.setMsg("请上传资质图片！");
				return page;
			}
			stdCompprofileFromDb.setProfileName(stdCompprofile.getProfileName());
			stdCompprofileFromDb.setProfileType(stdCompprofile.getProfileType());
			stdCompprofileFromDb.setProfileStarttime( DateUtil.parseDate(stdCompprofile.getProfileStarttimeStr()));
			stdCompprofileFromDb.setProfileEndtime( DateUtil.parseDate(stdCompprofile.getProfileEndtimeStr()));
			Date now =  new Date();
			Timestamp timestamp  = new Timestamp(now.getTime());
			stdCompprofileFromDb.setUpdDatetime(now);
			stdCompprofileFromDb.setUpdUser(user.getId());
			if (bidProjcompprofileManager.update(stdCompprofileFromDb)) {//更新企业资质
				StdCompprofileLog stdCompprofileLog = new StdCompprofileLog();
				BeanUtils.copyProperties(stdCompprofileLog, stdCompprofileFromDb);
				stdCompprofileLog.setLogId(UUID.randomUUID().toString());
				if (bidProjcompprofileManager.save(stdCompprofileLog) ){
					bidProjcompprofile.setComplainStatus(Constants.COMPLAIN_STATUS_0);//澄清状态0.提交1.澄清通过2澄清不通过
					bidProjcompprofile.setApplyType(Constants.APPLY_TYPE_MODIFY);//申请类型0修改申报1新增申报
					bidProjcompprofile.setComplainRemark(stdCompprofile.getComplainRemark());
					bidProjcompprofile.setComplainDatetime(timestamp);
					bidProjcompprofile.setUpdDatetime(timestamp);
					bidProjcompprofile.setUpdUser(user.getId());
					if(bidProjcompprofileManager.update(bidProjcompprofile)){//更新采购项目企业资质
						BidProjcompprofileLog bidProjcompprofileLog = new BidProjcompprofileLog();
						BeanUtils.copyProperties(bidProjcompprofileLog, bidProjcompprofile);
						bidProjcompprofileLog.setLogId(UUID.randomUUID().toString());
						bidProjcompprofileManager.save(bidProjcompprofileLog);
						page.setSuccess(true);
					}
				}
			}
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return page;
	}
	
	/**
	 *@category 去资审澄清结果页面
	 *@author 应晓川
	 *@date 2015年8月31日11:10:59
	 *@return
	 */
	@RequestMapping("/toComplainResult")
	public String toSysNoticeResult(String projId){
		request.setAttribute("projId", projId);
		return "/pro/project/bidProjcompprofile/complainResult";
	}
	
	/**
	 *@category 获取企业资质澄清结果列表数据
	 *@author 应晓川
	 *@date 2015年8月27日16:45:53
	 *@return
	 */
	@RequestMapping("/getComplainResultList")
	@ResponseBody
	public Pagination getComplainResultList(String projId){
		Pagination page = new Pagination(request);
		SysUser user=(SysUser) request.getSession().getAttribute(Constants.USERINFO);
		String compId = ((StdCompinfo )user.getInfo()).getCompId();
		try {
			page.getConditions().put("projId", projId);
			page.getConditions().put("compId", compId);
			page.getConditions().put("complainStatus", "3");//澄清状态0.提交1.澄清通过2澄清不通过
			page = bidProjcompprofileManager.getBidProjcompprofileResultList(page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
}
